<!-- 图片列表 -->
<template>
  <div class="image-uploader">
    <div v-if="!imgList.length && attrs.isDetail">无图片</div>
    <div class="imgList">
      <div
        class="block"
        v-for="item in imgList"
        :key="item.url"
      >
        <span class="demonstration">
          {{ item.name }} 
          <Icon class="trash" v-if="!attrs.isDetail" type="ios-trash" size="22" @click="handleRemove(item)" />
        </span>
        <el-image
          ref="authImg"
          style="width: 148px; height: 148px"
          @click="downLoad(item)"
          fit="fill">
          <div slot="placeholder" class="image-slot">
            加载中<span class="dot">...</span>
          </div>
        </el-image>
      </div>
    </div>
    <!-- 限制只能上传一张图片 -->
    <el-upload
      v-if="!attrs.isDetail && imgList.length < 1"
      :disabled="attrs.isPreview"
      ref="uploadImg"
      class="uploader"
      :action="uploadUrl"
      :headers="uploadHeaders"
      :data="uploadData"
      :file-list="imgList"
      list-type="picture-card"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      >
        <i class="el-icon-plus uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import formMixin from 'vue-ele-form/lib/mixins/formMixin'
import coverApi from '@/api/cover'
import dataEleApi from '@/api/dataElement'

export default {
  name: 'image-uploader',
  mixins: [formMixin],
  data() {
    return {
      uploadHeaders: { authorization: localStorage.Authorization ? `Bearer ${localStorage.Authorization}` : '' },
      uploadUrl: dataEleApi.getDataUploadUrl(),
      uploadData: { bizId: '0' },
      imgList: [],
    }
  },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    // 响应处理函数
    responseFn: Function,
  },
  methods: {
    downLoad(file) {
      coverApi.plantaskDownloadFile(file.fileId)
    },
    handleAvatarSuccess(res, file) {
      if (!this.imgList || !Array.isArray(this.imgList)) {
        this.imgList = [];
      }
      const imgInfo = {
        name: file.name,
        url: file.url,
        fileId: res.data,
      }
      this.imgList.push(imgInfo)
      if (this.attrs.responseFn) {
        res = this.attrs.responseFn(res, file, this.imgList)
      }
      if (this.attrs.multiple) {
        this.$emit("input", this.imgList);
      } else {
        this.$emit("input", imgInfo);
      }
      // 上传成功
      this.$emit("success", res, this.imgList)
    },
    handleRemove(file) {
      this.$confirm({
        title:"删除",
        content: "是否确定删除?"
      }).then(() => {
        let index = this.imgList.findIndex(item => item.fileId === file.fileId)
        this.imgList.splice(index, 1)
      })
      
    },
    getImgUrl(fileId, index) {
      const imgUrl = dataEleApi.searchImg(fileId)
      Object.defineProperty(Image.prototype,"imgurl",{
        configurable:true,
        writable:true,
        enumerable:true
      })
      let request = new XMLHttpRequest();
      request.responseType = "blob";
      request.open("get", imgUrl,true);
      request.setRequestHeader('authorization',this.uploadHeaders.authorization);
      let imgRef = this.$refs.authImg[index]
      request.onreadystatechange = e => {
        if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
          imgRef.src = URL.createObjectURL(request.response); // 将生成的blob对象的值赋值给img的src属性
          imgRef.onLoad = () => {
            URL.revokeObjectURL(imgRef.src); // 在图片加载完成后释放
          }
        }
      }
      request.send(null)
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.imgList = newVal
        this.$nextTick(() => {
          this.imgList.forEach((item, index) => {
            this.getImgUrl(item.fileId, index)
          })
        })
      }
    },
    immediate: true
  },
}
</script>

<style lang="less" scoped>
.image-uploader {
  display: flex;
  align-items: center;
  .imgList {
    display: flex;
    margin-bottom: 40px;
    gap: 10px;
    .block {
      display: flex;
      flex-direction: column;
      .demonstration {
        display: flex;
        align-items: center;
        margin: 0 auto;
        .trash:hover {
          cursor: pointer;
        }
      }
      .image-slot {
        width: 148px;
        height: 148px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: rgb(245,247,250);
      }
    }
  }
  
  .uploader {
    // margin-top: 40px;
    margin-left: 10px;
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover {
        border-color: #409EFF;
      }
    }
    .uploader-icon {
      font-size: 28px;
      color: #ccd6e4;
      width: 148px;
      height: 148px;
      line-height: 148px;
      text-align: center;
    }
  }
}
</style>